package com.jianbing.util;

import java.security.MessageDigest;
import java.util.*;

import net.sf.json.JSONObject;

/**
 * Created by LFL on 2017/4/18
 */
public class SignUtil {

	/**
	 * 校验签名
	 *
	 * @param data
	 *            请求参数
	 * @param appSecret
	 *            从数据库中取出的appSecret
	 * @return 返回sign
	 */
	public static String generateSign(Map<String, String> data, String appSecret) {
		List<String> list = new ArrayList<String>();
		for (Map.Entry<String, String> entry : data.entrySet()) {
			String key = entry.getKey();
			if (key == "sign") {
				continue;
			}
			list.add(key);
		}
		Collections.sort(list, new Comparator<String>() {
			public int compare(String arg0, String arg1) {
				return arg0.compareTo(arg1);
			}
		});
		String StringA = "";
		String connector = "";
		for (Map.Entry<String, String> entry : data.entrySet()) {
			String key = entry.getKey();
			if (key == "sign") {
				continue;
			}
			if (entry.getValue() == null || entry.getValue().length() == 0) {
				continue;
			}
			StringA += connector + key + "=" + entry.getValue();
			connector = "&";
		}
		StringA += connector + "appsecret=" + appSecret;
		return MD5Util.convert(StringA).toUpperCase();
	}

	/**
	 * 
	 * 获取签名
	 * 
	 * @author cwl
	 * @date 2017年5月11日
	 *
	 * @param map
	 * @param appSecret
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String createSign(SortedMap<String, String> map, String appSecret) {
		StringBuffer param = new StringBuffer();
		Set set = map.entrySet();
		Iterator it = set.iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			if (entry.getKey() != null && StringUtils.isNotEmpty(entry.getValue()) && !"sign".equals(entry.getKey())) {
				param.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		param.append("appSecret=" + appSecret);
		return MD5Util.MD5Encode(param.toString(), "UTF-8").toUpperCase();
	}

	/**
	 * 
	 * 签名校验
	 * 
	 * @author cwl
	 * @date 2017年5月11日
	 *
	 * @param sign
	 * @param map
	 * @param appSecret
	 * @return
	 */
	public static boolean checkSign(String CustomerSign, SortedMap<String, String> map, String appSecret) {
		String sign = createSign(map, appSecret);
		if (CustomerSign.equals(sign)) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public static boolean checkSign(String CustomerSign, JSONObject jsonParams, String appSecret) {
		SortedMap<String, String> map = new TreeMap<>();
		Iterator<String> keys = jsonParams.keys();
		while (keys.hasNext()) {
			String key = keys.next();
			map.put(key, jsonParams.getString(key));
		}
		return checkSign(CustomerSign, map, appSecret);
	}
}
